package service

import (
	"teacher-helper/dao"
	"teacher-helper/models"
	"teacher-helper/models/request"
)

func AddOneSemester(Semester models.SysSemester) error {
	return dao.DB.Create(&Semester).Error
}

func GetSemesterList(queryInfo request.QueryInfo) (Semesters []models.SysSemester, total int, err error) {
	if queryInfo == (request.QueryInfo{}){
		err = dao.DB.Find(&Semesters).Count(&total).Error
		return
	}
	if queryInfo.Query == "" {
		if err = dao.DB.Model(&models.SysSemester{}).Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&Semesters).Error
	} else {
		if err = dao.DB.Model(&models.SysSemester{}).Where("name like ?", "%"+queryInfo.Query+"%").Count(&total).Error; err != nil {
			return
		}
		err = dao.DB.Where("name like ?", "%"+queryInfo.Query+"%").Limit(queryInfo.PageSize).Offset((queryInfo.PageNum - 1) * queryInfo.PageSize).Find(&Semesters).Error
	}
	return
}

func GetSemesterMap() (semester_map map[int]string, err error) {
	var semesters []models.SysSemester
	semester_map = make(map[int]string)
	err = dao.DB.Find(&semesters).Error
	for _, semester := range semesters{
		semester_map[semester.ID] = semester.Name
	}
	return
}

func GetSchoolYearList() (school_year_map map[string][]int, err error) {
	var Semesters []models.SysSemester
	err = dao.DB.Find(&Semesters).Error
	school_year_map = make(map[string][]int)
	for _, semester := range Semesters{
		school_year_map[semester.SchoolYear] = append(school_year_map[semester.SchoolYear], semester.ID)
	}
	return
}

func UpdateSemester(Semester models.SysSemester) error {
	return dao.DB.Model(&models.SysSemester{}).Where(&models.SysSemester{ID:Semester.ID}).Update(&models.SysSemester{Name:Semester.Name}).Error
}

func DeleteSemester(id int) error {
	return dao.DB.Delete(&models.SysSemester{ID:id}).Error
}
